package cn.tedu.v1.service.impl;

import cn.tedu.v1.exception.ServiceException;
import cn.tedu.v1.mapper.UserRoleMapper;
import cn.tedu.v1.model.User;
import cn.tedu.v1.mapper.UserMapper;
import cn.tedu.v1.model.UserRole;
import cn.tedu.v1.service.IUserService;
import cn.tedu.v1.vo.RegisterVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户列表 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-07-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    private PasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public void registerUser(RegisterVo registerVo) {
        //验证用户名是否重复
        User user = userMapper.findUserByUsername(registerVo.getUsername());
        if (user != null) {
            throw new ServiceException("用户名已存在");
        }
        user = userMapper.findUserByEmail(registerVo.getEmail());
        if (user != null) {
            throw new ServiceException("邮箱已被注册");
        }
        User u = new User();
        String pwd = "{bcrypt}" + encoder.encode(registerVo.getPassword());
        u.setUsername(registerVo.getUsername())
                .setEmail(registerVo.getEmail())
                .setPassword(pwd);
        int num = userMapper.insert(u);
        if (num != 1) {
            throw new ServiceException("服务器忙,请稍后再试");
        }
        UserRole userRole = new UserRole();
        userRole.setRoleId(3);
        userRole.setUserId(u.getId());
        num = userRoleMapper.insert(userRole);
        if (num != 1) {
            throw new ServiceException("服务器忙,请稍后再试");
        }

    }
}
